package io.github.wx.service;

import com.jfinal.aop.Duang;
import com.jfinal.kit.JMap;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.redis.Redis;
import io.github.wx.common.constant.EnumFuctionStatus;
import io.github.wx.common.easyui.DataGrid;
import io.github.wx.common.shiro.cache.RedisSessionDAO;
import io.github.wx.common.shiro.kit.PasswordKit;
import io.github.wx.common.shiro.kit.ShiroSessionKit;
import io.github.wx.dao.model.SysUser;
import io.github.wx.dao.model.SysUserRole;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by jie on 2017/4/7.
 * 用户信息Service
 */
public class UserService {

    /**
     * 获取用户
     *
     * @param user SysUser
     * @return sysUserList
     */
    public List<SysUser> getUserByUsername(SysUser user) {
        user.setDelFlag(EnumFuctionStatus.DEL_STATUS.getCode());
        SqlPara sqlPara = SysUser.dao.getSqlPara("user.findUserByName", user);
        return SysUser.dao.find(sqlPara);
    }

    /**
     * 分页查询用户信息
     *
     * @param page page
     * @param rows rows
     * @return DataGrid
     */
    public DataGrid<SysUser> getUserPage(Integer page, Integer rows) {
        String select = "SELECT `user`.user_id, `user`.username, `user`.`password`, `user`.salt, `user`.user_desc , `user`.img, `user`.create_time, `user`.update_time, `user`.del_flag, role.role_name ";
        String sqlExcepteSelect = "FROM sys_user AS `user`INNER JOIN sys_user_role AS ur ON `user`.user_id = ur.user_id INNER JOIN sys_role AS role ON ur.role_id = role.role_id where user.del_flag <> ? AND role.del_flag = ?";
        Page<SysUser> userPage = SysUser.dao.paginate(page, rows, select, sqlExcepteSelect, EnumFuctionStatus.DEL_STATUS.getCode(), EnumFuctionStatus.NORMAL_STATUS.getCode());
        return new DataGrid<SysUser>(userPage);
    }

    /**
     * 新增用户
     *
     * @param sysUser 用户信息
     * @param roleId  角色ID
     */
    public void addUser(SysUser sysUser, int roleId) {
        //处理密码
        String passpwd = sysUser.getPassword();
        Map<String, String> map = PasswordKit.encryptPassword(passpwd);
        String password = map.get(PasswordKit.ENCRYPT_KEY);
        String salt = map.get(PasswordKit.ENCRYPT_SALT);
        sysUser.setPassword(password);
        sysUser.setSalt(salt);
        sysUser.save();
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getUserId());
        userRole.setRoleId(roleId);
        userRole.save();
    }

    /**
     * 根据用户ID查询用户信息包含角色信息
     *
     * @param userId ID
     * @return SysUser
     */
    public SysUser getUserById(int userId) {
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setDelFlag(EnumFuctionStatus.DEL_STATUS.getCode());
        SqlPara sqlPara = SysUser.dao.getSqlPara("user.findUserById", user);
        return SysUser.dao.findFirst(sqlPara);
    }

    /**
     * 修改用户信息
     *
     * @param sysUser   user
     * @param oldPwd    旧密码
     * @param oldRoleId 旧角色ID
     */
    public void updateUser(SysUser sysUser, String oldPwd, int oldRoleId) {
        String password = sysUser.getPassword();
        int roleId = sysUser.getRoleId();
        if (!oldPwd.equals(password)) {//不相等说明修改了密码
            Map<String, String> resultMap = PasswordKit.encryptPassword(password);
            sysUser.setPassword(resultMap.get(PasswordKit.ENCRYPT_KEY));
            sysUser.setSalt(resultMap.get(PasswordKit.ENCRYPT_SALT));
        } else if (oldRoleId != roleId) {//不相等说明修改了角色
            JMap map = new JMap();
            map.put("user_id", sysUser.getUserId());
            map.put("role_id", oldRoleId);
            SqlPara sqlPara = SysUser.dao.getSqlPara("user.findUserRole", map);
            SysUserRole userRole = SysUserRole.dao.findFirst(sqlPara);
            userRole.delete();
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRole.save();
        }
        sysUser.setUpdateTime(new Date());
        sysUser.update();

        /*强制下线被改密码的用户*/
        if (!oldPwd.equals(password)) {
            ShiroSessionKit.delSession(sysUser.getUsername());
        }
    }

    /**
     * 根据ID删除用户（逻辑删除）
     *
     * @param userId 用户ID
     */
    public void deleteUserById(int userId) {
        JMap map = new JMap();
        map.put("user_id", userId);
        SqlPara sqlPara = SysUser.dao.getSqlPara("user.findUserRole", map);
        SysUserRole userRole = SysUserRole.dao.findFirst(sqlPara);
        userRole.delete();
        SysUser user = SysUser.dao.findById(userId);
        user.setUpdateTime(new Date());
        user.setDelFlag(EnumFuctionStatus.DEL_STATUS.getCode());
        user.update();
    }

    /**
     * 根据ID锁定用户
     *
     * @param userId 用户ID
     */
    public void LockUserById(int userId) {
        SysUser user = SysUser.dao.findById(userId);
        user.setUpdateTime(new Date());
        user.setDelFlag(EnumFuctionStatus.BAD_STATUS.getCode());
        user.update();
    }

}
